import { get4hour } from "@/utils/currentDate";
import { getMeasurements } from "@/api/assignments";
import { taskDownloadZK } from "@/api/zk";
import {
  getChild,
  getTreeNode,
  getAllParentNodes
} from "@/views/centralizedControl/js/utils";
import { formatDate } from "@/filter/index";
import {
  getTaskFeedback,
  formulaRecordInfos,
  getDevicesV2Tree
} from "@/api/deviceOperation";
import initMqtt from "@/views/common/js/device/mqttUtils.js";
import {
  MAP_DEATIL_PREHEAT,
  ONE_FURNACE,
  TWO_FURNACE,
  THREE_FURNACE,
  CHEMICAL_FORMULA_INFO,
  CHART_KEYS_PV,
  MAP_DEATIL_CHEMISTRY_25,
  MAP_DEATIL_CHEMISTRY_nitrogenFlow,
  Z16_TOKEN,
  Z17_TOKEN,
  Z2_TOKEN
} from "@/views/centralizedControl/deviceOperation/constant.js";
import { CHART_KEYS_Z16 } from "@/views/centralizedControl/deviceOperation/vacuumFurnace/Z16/constant";
import { CHART_KEYS_Z17 } from "@/views/centralizedControl/deviceOperation/vacuumFurnace/Z17/constant";
import { CHART_KEYS_Z2 } from "@/views/centralizedControl/deviceOperation/vacuumFurnace/Z2/constant";

import { POINT_CHART_TYPES } from "@/utils/local";
import { getDeviceAttributes } from "@/api/deviceType";

import { restSql } from "@/api/taos";
import {
  renderSql,
  setIntervalTime
} from "@/views/centralizedControl/historicalTasksSearch/Curve/js/constent";
import _ from "lodash";
const startDate = get4hour();
const state = {
  controlDeviceInfo: {}, //当前选中的设备信息
  area123: {}, //三个温区的数据
  area123Curve: [], // 三个温区的历史曲线
  client: null, //当前的mqtt对象
  realTimeData: {}, //mqtt接受的数据
  deviceTreeData: [], //左侧设备树
  taskFeedbackTable: [], //任务反馈
  formulaRecordInfosList: [], //实时数据的表格数据
  taskDownLoadInfos: [], //任务下发的列表
  deviceAttributesList: [], //设备下的点位
  deviceTempAreaCount: 1 //当前设备的温区数量
};
const getters = {
  // 获取任务id
  getTaskId: state => {
    const taskId = state.taskFeedbackTable.length
      ? state.taskFeedbackTable[0].formulaDownId
      : "";
    return taskId;
  }
};
const mutations = {
  setDeviceAttributesList(state, data) {
    state.deviceAttributesList = data;
  },
  setTaskDownLoadInfos(state, data) {
    state.taskDownLoadInfos = data;
  },
  setDeviceInfo(state, data) {
    state.controlDeviceInfo = data;
  },
  setArea123(state, data) {
    state.area123 = data;
  },
  setArea123Curve(state, data) {
    state.area123Curve = data;
  },
  setClient(state, data) {
    state.client = data;
  },
  setRealTimeData(state, data) {
    state.realTimeData = data;
  },
  setDeviceTreeData(state, data) {
    state.deviceTreeData = data;
  },
  setTaskFeedbackTable(state, data) {
    state.taskFeedbackTable = data;
  },
  setFormulaRecordInfosList(state, data) {
    state.formulaRecordInfosList = data;
  },
  clearData(state) {
    state.area123 = {};
    state.area123Curve = {};
    state.realTimeData = {};
    state.formulaRecordInfosList = [];
    state.taskFeedbackTable = [];
  },
  endClent(state, data) {
    if (state.client) {
      console.log("开启之前 先关闭 :>> ");
      state.client.end(true);
      state.client = null;
    }
  },
  setAttrData(state, data) {},
  setDeviceTempAreaCount(state, count) {
    state.deviceTempAreaCount = count;
  }
};

const actions = {
  // 获取温区数量
  async getTempAreaCount({ state, commit }, params) {
    const { type, tenantToken, deviceEventType, assignmentToken } = params;
    const typeStr = `max(meta_${type}) as ${type}`;
    return new Promise(async (resolve, reject) => {
      restSql(
        "select first(type) as type, " +
          typeStr +
          " from td_" +
          tenantToken +
          ".`" +
          assignmentToken +
          "` where type=='Measurement'"
      )
        .then(res => {
          if (res.data.data && res.data.data.length) {
            console.log("当前设备的温区数量 :>> ", res.data.data[0][1]);
            if (res.data.data[0] && res.data.data[0].length) {
              commit("setDeviceTempAreaCount", res.data.data[0][1] || 1);
            } else {
              commit("setDeviceTempAreaCount", 1);
            }
          }
          resolve();
        })
        .catch(e => {
          console.log("当前设备的温区数量 :>> ", e);
          commit("setDeviceTempAreaCount", 1);
          resolve();
        });
    });
  },

  // 根据设备获取点位
  async getDeviceAttributes({ state, commit }, params) {
    return new Promise(async (resolve, reject) => {
      try {
        const res = await getDeviceAttributes(
          {
            page: 1,
            pageSize: 1000000
          },
          params.deviceToken
        );
        const attributesList = res.data.results.filter(item => {
          let c = item.isChart.slice(",");
          return c.includes(POINT_CHART_TYPES[0].key);
        });
        const sqlStr = renderSql({
          ...params,
          type: attributesList.map(item => item.token)
        });
        restSql(sqlStr)
          .then(results => {
            // 设置点位下的数据
            const sqlObj = results.data;
            attributesList.forEach(item => {
              // 动态获取头部的下标
              const index = sqlObj.head.findIndex(
                h => h == item.token.toLowerCase() //涛思的不区分大小写
              );
              _.set(item, "dataIndex", index);
              // 添加一个空的放数据的数据
              _.set(item, "data", []);
              _.set(item, "times", []);
              if (sqlObj.data.length) {
                sqlObj.data.forEach(d => {
                  item.data.push(d[item.dataIndex]);
                  // x轴的时间在数组中第0个里边
                  item.times.push(formatDate(d[0]));
                });
              }
            });
            console.log("当前设备的点位 :>> ", attributesList);
            commit("setDeviceAttributesList", attributesList);
            resolve();
          })
          .catch(err => {
            attributesList.forEach(item => {
              _.set(item, "data", []);
              _.set(item, "times", []);
            });
            commit("setDeviceAttributesList", attributesList);
            resolve();
          });
      } catch (error) {}
    });
  },
  // 任务列表
  async getTaskDownLoadInfos({ state, commit }, deviceToken) {
    return new Promise(async (resolve, reject) => {
      const res = await taskDownloadZK({
        parentTaskNumber: "ROOT",
        deviceToken: deviceToken,
        taskStatus: 0
      });
      const { results } = res.data;
      // this.tableData = results;
      commit("setTaskDownLoadInfos", results);
      resolve();
    });
  },
  // 任务反馈
  async getTaskFeedback({ state, commit, dispatch }, deviceToken) {
    return new Promise(async (resolve, reject) => {
      const res = await getTaskFeedback({
        taskStatus: 1,
        deviceToken: deviceToken
      });
      const { results } = res.data;
      // 保存任务号 后续查询曲线表格
      if (results.length) {
        commit("setTaskFeedbackTable", results);
        // this.taskId = this.taskFeedbackTable[0].taskId;
      } else {
        commit("setTaskFeedbackTable", []);
        // this.getTaskFeedbackNone();
      }
      resolve();
    });
  },
  // 远程监控的曲线表格(依赖任务反馈的任务号)
  async getFormulaDownloadInfoList({ commit }, formulaDownId) {
    // 拿任务反馈的任务号查询
    if (formulaDownId) {
      const res = await formulaRecordInfos({
        formulaDownid: formulaDownId
      });
      const { results } = res.data;
      commit("setFormulaRecordInfosList", results);
    } else {
      commit("setFormulaRecordInfosList", []);
    }
  },
  // 树设备
  async getDevicesV2Tree({ state, commit, dispatch }, token) {
    return new Promise(async (resolve, reject) => {
      // 请求之前清空
      const res = await getDevicesV2Tree();
      const { data } = res;
      if (!data || !data.length) {
        reject("暂无设备信息");
      }
      // 给最后一级排序
      const newData = renderTreeSortBy(data);
      // 手动添加一个sort字段 排序
      newData.forEach(item => {
        item.children = _.sortBy(item.children, "sort");
      });
      commit("setDeviceTreeData", newData);

      let row = {};
      // 是否是从车间点击过来的
      if (token) {
        row = getTreeNode(newData, token);
      } else {
        // 取出第一个
        row = getDeviceRow(newData);
      }
      const parentNodes = getAllParentNodes(newData, row.token);
      console.log("parentNodes :>> ", parentNodes);
      const names = parentNodes.map(item => item.name).reverse();
      commit("setDeviceInfo", { ...row, deviceParentName: names.join("/") });
      // 赋值token,上级钻取存在赋值否则从数组中第一个赋值
      // if (token) {
      //     // getQueryDeviceRow();
      // } else {
      //     // getDeviceRow();
      // }
      resolve();
    });
  },
  // mqtt接收数据
  receiveData({ state, commit, dispatch }, data) {
    return new Promise(async (resolev, reject) => {
      const { tenantToken, assignmentToken, deviceToken } = data;
      // 打开是之前判断是否开启,开启则关闭
      commit("endClent");
      // var param = {
      //   url: "ws://broker.emqx.io:8083/mqtt"
      // };
      // const tenantTopic = `testtopic${deviceToken}/#`;
      // console.log("param :>> ", tenantTopic);
      var param = {
        url: process.env.VUE_APP_MQTT_WS_URL + "/mqtt"
      };

      const tenantTopic = `$avic/superlink/iot/${tenantToken}/${deviceToken}/measurement`;
      const initmqtt = new initMqtt(param);
      const client = initmqtt.connect(() => {
        console.log("mqtt连接成功,开始订阅主题", tenantTopic);

        state.client.subscribe(tenantTopic);
      });
      commit("setClient", client);
      const res = await dispatch("onMessageArrived");
      resolev(res);
    });
  },
  // mqtt订阅 取数据
  onMessageArrived({ state, commit }) {
    return new Promise(async (resolev, reject) => {
      state.client.on("message", (topic, message) => {
        if (message && message.toString()) {
          var obj = JSON.parse(message.toString());
          const { request } = obj;
          if (!request) {
            reject("metadata不存在");
            return;
          }

          if (!request.metadata) {
            reject("metadata不存在");
            return;
          }

          console.log("mqtt订阅消息 :>> ", obj.request.metadata.meter1RealTemp);
          console.log("mqtt订阅消息 :>> ", obj.request.metadata.meter2RealTemp);
          const area123 = {
            ...request.metadata,
            value: request.value
          };
          commit("setRealTimeData", request);

          commit("setArea123", area123);
          resolev(request);
        }
      });
    });
  },
  // 获取曲线图
  getAssignmentsByToken({ state, commit }, params) {
    return new Promise(async (resolev, reject) => {
      // 获取之前先清空实时和历史的曲线数据
      // 获取前四个小时
      const sqlStr = renderSql({
        ...params
      });
      try {
        const results = await restSql(sqlStr);
        // 设置点位下的数据
        commit("setAttrData", results.data);
        console.log("sqlStr :>> ", results.data);
        resolev();
      } catch (error) {}
      // getMeasurements(
      //   {
      //     startDate,
      //     page: 1,
      //     pageSize: 100
      //   },
      //   assignmentToken
      // )
      //   .then(res => {
      //     const { results } = res.data;
      //     if (results.length) {
      //       commit("setArea123Curve", results);
      //     }
      //     resolev(results);
      //   })
      //   .catch(e => {
      //     commit("setArea123Curve", []);
      //   });
    });
  }
  // //  获取设备详情 三个区
  // getAssignmentsByToken3({ state, commit }, assignmentToken) {
  //   return new Promise((resolev, reject) => {
  //     getMeasurements(
  //       {
  //         page: 1,
  //         pageSize: 1
  //       },
  //       assignmentToken
  //     )
  //       .then(res => {
  //         const { results } = res.data;

  //         if (results.length) {
  //           commit("setArea123", {
  //             ...results[0].metadata,
  //             value: results[0].value
  //           });
  //         } else {
  //           commit("setArea123", {});
  //         }
  //         resolev(results);
  //       })
  //       .catch(e => {
  //         commit("setArea123", {});
  //       });
  //   });
  // }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
};
function getDeviceRow(treeData) {
  const lastChild = getChild(treeData);
  return lastChild ? lastChild : "";
}

// 给最后一级排序
function renderTreeSortBy(data) {
  const deepData = _.cloneDeep(data);
  treeToArray(deepData);
  //  token: 父节点的token
  function treeToArray(deepData, token) {
    deepData.forEach(item => {
      // 设置温区数量
      if (ONE_FURNACE.includes(item.token)) {
        _.set(item, "_tempAreaCount", 1);
        _.set(item, "_chartKeys", [CHART_KEYS_PV[0]]);
      }
      if (TWO_FURNACE.includes(item.token)) {
        _.set(item, "_tempAreaCount", 2);
        _.set(item, "_chartKeys", [CHART_KEYS_PV[0], CHART_KEYS_PV[1]]);
      }
      if (THREE_FURNACE.includes(item.token)) {
        _.set(item, "_tempAreaCount", 3);
        _.set(item, "_chartKeys", [
          CHART_KEYS_PV[0],
          CHART_KEYS_PV[1],
          CHART_KEYS_PV[2]
        ]);
      }
      // 添加一个排序字段
      // 化学
      if (item.token == "RBC531_HX") {
        _.set(item, "sort", 1);
      }
      // 常规
      if (item.token == "RBC531_CG") {
        _.set(item, "sort", 0);
      }
      // 真空
      if (item.token == "RBC531_ZK") {
        _.set(item, "sort", 2);
      }
      // 辅机
      if (item.token == "RBC531_FJ") {
        _.set(item, "sort", 3);
      }
      if (token == "RBC531_HX" || token == "RBC531_CG") {
        _.set(item, "_msgContentList", MAP_DEATIL_PREHEAT);
        // 设置炉子的配方参数
        _.set(item, "_formulaInfo", getFormulaTabArr(item.token));
      }
      if (item.token == Z16_TOKEN) {
        _.set(item, "_chartKeys", CHART_KEYS_Z16);
      }
      if (item.token == Z17_TOKEN) {
        _.set(item, "_chartKeys", CHART_KEYS_Z17);
      }
      if (item.token == Z2_TOKEN) {
        _.set(item, "_chartKeys", CHART_KEYS_Z2);
      }
      // 化学炉-25 基础信息 (包括了7-8-11-25)
      if (
        item.token == "1307128" ||
        item.token == "1308014" ||
        item.token == "1308028" ||
        item.token == "1308025"
      ) {
        // Chemistry
        _.set(item, "_msgContentList", MAP_DEATIL_CHEMISTRY_25);
      }
      // 氮气流量 的化学炉子
      if (item.token == "1308019" || item.token == "1308022") {
        _.set(item, "_msgContentList", MAP_DEATIL_CHEMISTRY_nitrogenFlow);
      }

      if (item.children && item.children.length) {
        if (item.type == 2) {
          item.children = _.sortBy(item.children, function(li) {
            return Number(li.name.replace(/[^\d]/g, ""));
          });
        }
        treeToArray(item.children, item.token);
      }
    });
  }

  return deepData;
}

// 获取不同炉子的配方参数
function getFormulaTabArr(key) {
  return CHEMICAL_FORMULA_INFO;
}
